from tortoise.expressions import Q

from app.core.crud import CRUDBase
from app.models.orders import OrdersReceive
from app.schemas.orders import OrdersReceiveUpdate,OrdersReceiveCreate


class OrdersReceiveController(CRUDBase[OrdersReceive, OrdersReceiveCreate, OrdersReceiveUpdate]):
    def __init__(self):
        super().__init__(model=OrdersReceive)

    async def do_list(self, page: int, page_size: int, search: Q = Q()):
        query = self.model.filter(search)
        total = await query.count()
        objs =  await query.offset((page - 1) * page_size).limit(page_size).order_by('-id')
        data = [await obj.to_dict(exclude_fields=["updated_at","deleted_at"]) for obj in objs]
        return total, data

    async def do_create(self, obj_in: OrdersReceiveCreate):
        ##设为默认
        if obj_in.is_default:
            await OrdersReceive.all().update(is_default=False)
        await self.create(obj_in=obj_in)
        return True

    async def do_update(self, obj_in: OrdersReceiveUpdate):
        ##设为默认
        if obj_in.is_default:
            await OrdersReceive.all().update(is_default=False)
        await self.update(id=obj_in.id, obj_in=obj_in)
        return True

    async def do_delete(self, search: Q = Q()):
        await self.remove_q(search)
        return True


orders_receive_controller = OrdersReceiveController()
